/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package location.district;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "location_district")
@ViewScoped
public class Main extends Beans {
    //Variables de importación General

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    //Variables de importación otros modulos
    //Variables del modulo
    private Find location_districtFind = new Find();
    private List<Beans> location_districtList = new ArrayList<>();
    //Variables locales
    private Map<String, String> map = new LinkedHashMap<>();
    private String sql;

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    public void load() {
        try {
            sql = "SELECT * "
                    + "FROM public.v_localizacion_distrito "
                    + "WHERE id =  " + logged.getDetailId();
            ResultSet rsts = persistencia.executeRsts(sql);
            while (rsts.next()) {
                setId(rsts.getInt("id"));
                setNombre(rsts.getString("nombre"));
            }
            persistencia.dbDisconnect();
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {
            //se carga el mapa con los valores
            map.clear();
            map.put("id_provincia = " + getId_provincia().toString(), " AND ");
            map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (location_districtFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.localizacion_distrito (id_provincia, nombre) "
                    + "VALUES (" + getId_provincia() + ",'" + getNombre() + "')";

            //Inserta la información del registro
            persistencia.executeUpdate(sql);

            //Localiza el id del registro recien insertado, con la llave única
            location_districtList = location_districtFind.byMap(map);

            //Asigna el id del registro insertado a la variable global
            logged.setDetailId(location_districtList.get(0).getId());

            throw new Exc("m1");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public Integer insert(Integer id_provincia, String nombre) throws Exc, SQLException, Exception {
        map.clear();
        map.put("id_provincia = " + id_provincia, " AND ");
        map.put("lower(nombre) = '" + nombre.toLowerCase() + "'", " ");

        if (location_districtFind.byExist(map)) {
            throw new Exc("m5");
        }

        sql = "INSERT INTO public.localizacion_distrito (id_provincia, nombre) "
                + "VALUES (" + id_provincia + ",'" + nombre + "')";

        //Inserta la información del registro
        persistencia.executeUpdate(sql);

        location_districtList = location_districtFind.byMap(map);
        return location_districtList.get(0).getId();
    }

    public void update() {
        try {
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }
            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m6");
            }

            //carga el mapa con los valores
            map.clear();
            map.put("id <> " + logged.getDetailId(), " AND ");
            map.put("id_provincia = " + getId_provincia(), " AND ");
            map.put("lower(nombre) = '" + getNombre().toLowerCase() + "'", " ");

            //Verifica si el registro existe, de lo contrario lo inserta
            if (location_districtFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.localizacion_distrito SET "
                    + "id_provincia = " + getId_provincia() + ", "
                    + "nombre='" + getNombre() + "'"
                    + " WHERE id =" + logged.getDetailId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getDetailId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getDetailId());

            logged.setDetailId(0);
            setNombre("");

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        sql = "DELETE FROM public.localizacion_distrito "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        logged.setDetailId(0);
        logged.setTempId(0);
        clearBeans();
    }

    public void selectedCountry(ValueChangeEvent event) {
        getCountryBeans().setId(Integer.parseInt(event.getNewValue().toString()));
        logged.setMasterId(0);
        logged.setDetailId(0);
        setNombre("");
    }

    public void selectedProvince(ValueChangeEvent event) {
        setId_provincia(Integer.parseInt(event.getNewValue().toString()));
        logged.setTempId(getId_provincia());
        setNombre("");
    }

    public void selectedDetailId(int detailId) {
        logged.setDetailId(detailId);
        load();
    }

    public void insertCountry() throws Exc, SQLException, Exception {
        location.general.Main paisMain = new location.general.Main();
        getCountryBeans().setId(paisMain.insert(getCountryBeans().getNombre()));
        getCountryBeans().setNombre("");
    }

    public void insertProvince() throws Exc, SQLException, Exception {
        location.province.Main cityMain = new location.province.Main();
        setId_provincia(cityMain.insert(getCountryBeans().getId(), getProvinceBeans().getNombre()));
        getProvinceBeans().setNombre("");
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }
}
